<template>
  <div id="app">
    <div class="chat-container">
      <div class="chat-header">
        <h1>AI 编程小助手</h1>
        <div class="memory-id">会话ID: {{ memoryId || '生成中...' }}</div>
      </div>
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
        >
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
        <div v-if="isLoading" class="message ai-message">
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <input 
          v-model="inputMessage" 
          @keyup.enter="sendMessage" 
          placeholder="请输入您的问题..." 
          :disabled="isLoading"
        />
        <button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
          {{ isLoading ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';

export default {
  name: 'App',
  setup() {
    const messages = ref([]);
    const inputMessage = ref('');
    const isLoading = ref(false);
    const messagesContainer = ref(null);
    const memoryId = ref('');

    // 生成随机memoryId
    const generateMemoryId = () => {
      return 'mem_' + Math.random().toString(36).substr(2, 9);
    };

    // 初始化memoryId
    onMounted(() => {
      memoryId.value = generateMemoryId();
    });

    // 滚动到底部
    const scrollToBottom = async () => {
      await nextTick();
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    };

    // 发送消息
    const sendMessage = async () => {
      const message = inputMessage.value.trim();
      if (!message || isLoading.value) return;

      // 添加用户消息
      messages.value.push({
        role: 'user',
        content: message,
        time: new Date().toLocaleTimeString()
      });

      // 清空输入框
      inputMessage.value = '';

      // 设置加载状态
      isLoading.value = true;
      
      // 滚动到底部
      scrollToBottom();

      try {
        // 添加AI消息占位符
        const aiMessageIndex = messages.value.length;
        messages.value.push({
          role: 'ai',
          content: '',
          time: new Date().toLocaleTimeString()
        });

        // 使用EventSource连接SSE
        const eventSource = new EventSource(`http://localhost:8081/api/ai/chat?memoryId=${memoryId.value}&message=${encodeURIComponent(message)}`);

        eventSource.onmessage = function(event) {
          if (event.data) {
            messages.value[aiMessageIndex].content += event.data;
            scrollToBottom();
          }
        };

        eventSource.onerror = function(err) {
          console.error('EventSource failed:', err);
          eventSource.close();
          isLoading.value = false;
          if (!messages.value[aiMessageIndex].content) {
            messages.value[aiMessageIndex].content = '抱歉，出现了一些问题，请稍后重试。';
          }
          scrollToBottom();
        };

      } catch (error) {
        console.error('Error sending message:', error);
        const lastMessage = messages.value[messages.value.length - 1];
        if (lastMessage && lastMessage.role === 'ai') {
          lastMessage.content = '抱歉，出现了一些问题，请稍后重试。';
        }
        isLoading.value = false;
        scrollToBottom();
      }
    };

    return {
      messages,
      inputMessage,
      isLoading,
      messagesContainer,
      memoryId,
      sendMessage
    };
  }
};
</script>

<style scoped>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 20px;
  height: calc(100vh - 40px);
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 900px;
  margin: 0 auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
}

.chat-header h1 {
  margin: 0;
  font-size: 24px;
  color: #42b983;
}

.memory-id {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
  background-color: #fafafa;
}

.message {
  display: flex;
  max-width: 85%;
}

.user-message {
  align-self: flex-end;
}

.ai-message {
  align-self: flex-start;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
}

.user-message .message-content {
  background-color: #42b983;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-content {
  background-color: #ffffff;
  color: #333;
  border: 1px solid #eee;
  border-bottom-left-radius: 4px;
}

.message-text {
  text-align: left;
  word-wrap: break-word;
  line-height: 1.5;
}

.message-time {
  font-size: 10px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.chat-input {
  display: flex;
  padding: 15px;
  border-top: 1px solid #eee;
  background-color: white;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 16px;
}

.chat-input input:focus {
  border-color: #42b983;
}

.chat-input button {
  margin-left: 10px;
  padding: 12px 24px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 16px;
}

.chat-input button:hover:not(:disabled) {
  background-color: #359c6d;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background: #42b983;
  border-radius: 50%;
  margin: 0 2px;
  display: inline-block;
  animation: typing 1s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

@media (max-width: 768px) {
  .chat-container {
    height: calc(100vh - 20px);
    margin: 10px;
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-header h1 {
    font-size: 20px;
  }
}
</style>